# !/usr/bin/env python
# -*-coding:utf-8 -*-
"""
# File       : task_view.py
# Time       ：2023/3/12 10:32
# Author     ：Y-aong
# version    ：python 3.7
# Description：
    任务视图
    task views
"""
from copy import deepcopy
from flask import request
from flask_restx import fields

from apis.orderlines import orderlines_ns
from apis.orderlines.models.task import Task, TaskInstance
from apis.orderlines.schema.task_schema import TaskSchema
from apis.orderlines.views import task_config_item_model
from public.api_utils.api_decorator import handle_api_error
from public.base_export_excel_view import BaseExportExcelView
from public.base_model import db
from public.base_response import generate_response, MarshalModel
from public.base_view import BaseView, BaseDetailsView

task = {
    'task_id': fields.String(description='任务ID'),
    'prev_id': fields.String(description='前置任务ID'),
    'next_id': fields.String(description='后续任务ID'),
    'task_index_id': fields.String(description='任务运行顺序ID'),
    'task_name': fields.String(description='任务名称'),
    'method_name': fields.String(description='任务执行方法名称'),
    'method_kwargs': fields.Raw(description='任务执行参数'),
    'task_type': fields.String(description='任务类型'),
    'task_module': fields.String(description='任务模块'),
    'module_version': fields.String(description='模块版本'),
    'task_config': fields.List(fields.Nested(task_config_item_model), description='任务配置'),
    'desc': fields.String(description='任务描述'),
    'process_id': fields.String(description='流程ID'),
}

task_detail = {'task_id': fields.String(description='任务ID')}

task_marshal = MarshalModel('task-config', orderlines_ns)


class TaskDetailView(BaseDetailsView):
    url = '/task/detail'

    def __init__(self, *args, **kwargs):
        super(TaskDetailView, self).__init__(*args, **kwargs)
        self.table_orm = Task
        self.table_schema = TaskSchema

    @handle_api_error()
    @orderlines_ns.doc(description="根据任务id获取任务配置详情")
    @orderlines_ns.expect(task_marshal.detail_request(task_detail))
    def get(self):
        """获取任务配置详情"""
        obj = db.session.query(Task).filter(Task.task_id == self.form_data.get('task_id'), Task.active == 1).first()
        task_info = TaskSchema().dump(obj)
        return generate_response(task_info)


class TaskView(BaseView):
    url = '/task'

    def __init__(self, *args, **kwargs):
        super(TaskView, self).__init__(*args, **kwargs)
        self.table_orm = Task
        self.table_schema = TaskSchema
        self.items = ['method_kwargs', 'result_config']
        self.is_logger = True

    def update_task_item(self, item_name: str):
        """修改巡视任务的item中的值"""
        obj = db.session.query(Task).filter(Task.id == self.table_id).first()
        info = TaskSchema().dump(obj)
        item: dict = deepcopy(info.get(item_name) or {})
        _item: dict = deepcopy(self.form_data.get(item_name))
        if item and _item and isinstance(_item, dict):
            for key, val in _item.items():
                if key and val:
                    item[key] = val
            self.form_data[item_name] = item

    def handle_request_params(self):
        if request.method == 'PUT':
            for key, val in self.form_data.items():
                if key in self.items:
                    self.update_task_item(key)

    @handle_api_error()
    @orderlines_ns.doc(description='获取任务配置列表')
    @orderlines_ns.expect(task_marshal.detail_request(task))
    @orderlines_ns.marshal_with(task_marshal.list_response(task))
    def get(self):
        """获取任务配置列表"""
        return super(TaskView, self).get()

    @handle_api_error()
    @orderlines_ns.doc(description='创建任务配置')
    @orderlines_ns.expect(task_marshal.create_request(task))
    @orderlines_ns.marshal_with(task_marshal.create_response())
    def post(self):
        """创建任务配置"""
        return super(TaskView, self).post()

    @orderlines_ns.doc(description='修改任务配置')
    @orderlines_ns.expect(task_marshal.update_request(task))
    @orderlines_ns.marshal_with(task_marshal.update_response())
    def put(self):
        """修改任务配置"""
        return super(TaskView, self).put()

    @orderlines_ns.doc(description='删除任务配置')
    @orderlines_ns.expect(task_marshal.delete_request())
    @orderlines_ns.marshal_with(task_marshal.delete_response())
    @handle_api_error()
    def delete(self):
        """删除任务配置"""
        with db.auto_commit():
            # 删除任务实例
            db.session.query(TaskInstance).filter(TaskInstance.task_id == self.form_data.get('task_id')).delete()
            # 删除任务
            db.session.query(Task).filter(Task.task_id == self.form_data.get('task_id')).delete()
        return generate_response(message='删除节点成功')


class TaskReportView(BaseExportExcelView):
    url = '/task/export'

    def __init__(self, *args, **kwargs):
        super(TaskReportView, self).__init__(*args, **kwargs)
        from datetime import datetime
        self.file_name = f'task_{datetime.now().strftime("%Y-%m-%d")}'
        self.columns = {
            'id': '序号',
            'process_id': '流程id',
            'task_id': '任务id',
            'task_name': '任务名称',
            'method_name': '方法名称',
            'insert_time': '创建时间',
            'update_time': '修改时间',
            'creator': '创建者',
            'task_type': '任务类型',
            'task_module': '任务模块',
            'module_version': '模块版本',
            'desc': '任务描述',
        }

    @handle_api_error()
    @orderlines_ns.doc(description='导出任务配置信息')
    @orderlines_ns.expect(task_marshal.detail_request(task))
    def post(self):
        """导出任务配置信息"""
        return super(TaskReportView, self).post()
